package com.example.admanagement.servlet;

import com.example.admanagement.Ad;
import com.example.admanagement.AdService;
import com.google.gson.Gson;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addAd")
public class AddAdServlet extends HttpServlet {
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        // 读取请求体中的JSON数据
        Ad ad = getAdFromRequest(request);
        AdService.Result<?> result = AdService.insertAd(ad);
        response.getWriter().write(gson.toJson(result));
    }

    private Ad getAdFromRequest(HttpServletRequest request) throws IOException {
        return new Gson().fromJson(request.getReader(), Ad.class);
    }
}